package com.dxy.shardingjdbc.utils;

import cn.hutool.core.date.LocalDateTimeUtil;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.HashSet;
import java.util.Random;

/**
 * @Description 订单工具类
 * @Author dangxianyue
 * @Date 2023/2/3 10:00
 */
public class IdUtil {

    /**
     * 生成订单编号（2位业务编码 + 6位日期 + 8位随机数 + 1位校验码 + 3位用户id）
     *
     * @param bizCode，业务编码
     * @param userId，用户id
     * @return
     */
    public static String getOrderCode(String bizCode, Long userId) {
        String rq = LocalDateTimeUtil.format(LocalDate.now(), "yyMMdd"); // 6位日期 YYMMDD
        int randomNum = random8(); // 8位随机数
        String userId3 = splitUserIdtoThreelength(userId);
        String check = getCheckCode(rq, randomNum + "", userId3);
        return bizCode + rq + randomNum + check + userId3;
    }

    /**
     * 生成8位随机数
     *
     * @return
     */
    private static int random8() {
        Random random = new Random();
        return 10000000 + random.nextInt(90000000);
    }

    /**
     * 截取三位长度的用户id
     *
     * @param userId
     * @return
     */
    private static String splitUserIdtoThreelength(Long userId) {
        userId = Math.abs(userId);

        if ((userId + "").length() == 3) {
            return userId + "";
        } else if ((userId + "").length() > 3) {
            return (userId + "").substring((userId + "").length() - 3, (userId + "").length());
        } else {
            return String.format("%03d", userId);
        }
    }

    /**
     * 获取校验位
     *
     * @param rq
     * @param randomNum
     * @param userId3
     * @return
     */
    private static String getCheckCode(String rq, String randomNum, String userId3) {
        int rqInt = Integer.parseInt(rq);
        int userIdInt = Integer.parseInt(userId3);
        int randomNumInt = Integer.parseInt(randomNum);
        int complementation = (userIdInt + randomNumInt) / rqInt;
        return getLast(complementation);
    }


    private static String getLast(int complementation) {
        String str = complementation + "";
        return str.substring(str.length() - 1, str.length());
    }

}
